package com.freedom.web.mymvc.route;

import java.io.BufferedReader;
import java.io.FileReader;
import java.lang.reflect.Method;
import java.util.HashMap;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.freedom.web.mymvc.utils.LoggerUtils;
import com.freedom.web.mymvc.utils.MyConstants;

import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;

@SuppressWarnings("resource")
public class MyRoute {
	// logger
	private static final Logger logger = LogManager.getLogger(MyRoute.class);
	private HashMap<String, Route> routes = new HashMap<String, Route>();// 只读情况下，不加锁，效率最高

	private MyRoute() {
	}

	public Route getRoute(String key) {
		return routes.get(key);
	}

	@SuppressWarnings("rawtypes")
	public void addRule(String key, String value) throws Exception {
		// 判断这个类是否是WorkerClass的实现
		Class<?> currentClass = Class.forName(value);
		if (false == com.freedom.web.mymvc.common.SystemInterface.class.isAssignableFrom(currentClass)) {
			throw new Exception("class: " + value
					+ " is not valid...should be interface implementation of (com.freedom.web.mymvc.route.MyRoute)");
		}
		// 测试通过，获取实例
		Object obj = currentClass.newInstance();
		// 获取方法
		Class[] argsClass = new Class[2];
		argsClass[0] = FullHttpRequest.class;
		argsClass[1] = FullHttpResponse.class;
		Method method = currentClass.getMethod("service", argsClass);
		// 构造route,存起来
		Route route = new Route(obj, method);
		routes.put(key, route);
		// 结束,等待被调用
		// 执行时只需要method.invoke(obj, args);
	}

	public static MyRoute instance = null;

	public static MyRoute getInstance() {
		return instance;
	}

	static {
		MyRoute route = new MyRoute();
		String routeFile = MyConstants.ROUTE_FILE;
		LoggerUtils.info(logger, "try to parse route file-" + routeFile);
		// 按行读取
		try {
			FileReader reader = new FileReader(routeFile);
			BufferedReader br = new BufferedReader(reader);
			String str = null;
			while ((str = br.readLine()) != null) {
				str = str.trim();
				if (str.length() == 0 || str.startsWith("#")) {
					continue;
				}
				// 有合法值
				String[] kv = str.split("\\s+");
				if (null == kv || kv.length != 2) {
					LoggerUtils.error(logger, "kv:" + kv.length);
					throw new Exception("parse " + str + " error");
				}
				route.addRule(kv[0], kv[1]);
			}
			// 释放文件句柄
			br.close();
			reader.close();
			// 赋值
			instance = route;
		} catch (Exception e) {
			LoggerUtils.error(logger, e.toString());
			System.exit(-1);
		}
	}

}